#[cfg(feature = "axstd")]
use axstd::println;

use axhal::fiomux::*;
use axhal::pwm::*;

// 定义风扇转速枚举
#[derive(PartialEq, Clone, Copy)]
pub enum FanSpeed {
    High,   // 高速可能现在目标正在距离运动,开发板计算产生热量大,加大散热力度
    Medium, // 中速可能现在目标正在移动,开发板计算产生热量中,调低散热力度
    Low,    // 低速可能现在目标正在停止,开发板计算产生热量小,调高散热力度
}

pub struct FanCtr {
    pwm_system: Option<PwmSystem>,
    speed: FanSpeed,
}

impl FanCtr {
    pub fn new() -> Self {
        Self {
            pwm_system: None,
            speed: FanSpeed::Medium,
        }
    }

    pub fn setup(&mut self) {
        // 初始化IOMUX
        println!("初始化IOMUX...");
        fiomux_init();

        // 设置PWM引脚复用
        println!("设置PWM引脚复用...");
        fiopad_set_pwm_mux(0, 1); // FPWM0_ID, PWM_TEST_CHANNEL=1
        println!("PWM引脚复用设置完成");

        // 初始化PWM控制器
        println!("正在初始化PWM控制器...");

        // 创建PWM系统实例
        let mut pwm_system = PwmSystem::new();

        // 配置通道1 (PWM_TEST_CHANNEL = FPWM_CHANNEL_1)
        let config = PwmConfig {
            frequency: 10000, // 10kHz频率
            duty_cycle: 0.2,  // 20%初始占空比
            counting_mode: 0, // Modulo模式
            deadtime_ns: None,
            use_fifo: false,
            output_behavior: 5, // FPWM_POLARITY_INVERTED (0b101)
            initial_value: 0,
        };

        println!("开始配置PWM通道...");
        // 获取PWM0控制器 (FPWM0_ID)
        let pwm_controller = pwm_system.controller(0).unwrap();

        // 配置并启用PWM通道
        match pwm_controller.configure_channel(1, config) {
            Ok(()) => {
                println!("PWM通道配置成功");
            }
            Err(e) => {
                println!("PWM通道配置失败: {}", e);
                return;
            }
        }

        self.pwm_system = Some(pwm_system);
    }

    fn set_duty(&mut self, duty: i32) {
        let new_duty_cycle: f32 = duty as f32 / 100.0;
        println!("准备设置新的占空比: {}%", duty);

        // 重新配置通道以应用新的占空比
        let new_config = PwmConfig {
            frequency: 10000, // 10kHz频率
            duty_cycle: new_duty_cycle,
            counting_mode: 0, // Modulo模式
            deadtime_ns: None,
            use_fifo: false,
            output_behavior: 5, // FPWM_POLARITY_INVERTED
            initial_value: 0,
        };

        let pwm_controller = self.pwm_system.as_mut().unwrap().controller(0).unwrap();
        match pwm_controller.configure_channel(1, new_config) {
            Ok(()) => {
                println!("风扇占空比已调整为{}%", duty);
            }
            Err(e) => {
                println!("调整风扇占空比失败: {}", e);
            }
        }

        // 重新启用通道
        let pwm_controller = self.pwm_system.as_mut().unwrap().controller(0).unwrap();
        if let Err(e) = pwm_controller.enable_channel(1) {
            println!("重新启用PWM通道失败: {}", e);
        }
    }

    pub fn run(&mut self) {
        let duty: i32 = 50; // 50%占空比,占空比越小风扇旋转越快

        self.speed = FanSpeed::Medium;
        self.set_duty(duty);
    }

    pub fn set_speed(&mut self, speed: FanSpeed) {
        if self.speed == speed {
            return;
        }

        self.speed = speed;
        let duty: i32; // 占空比越小风扇旋转越快

        match speed {
            FanSpeed::High => {
                println!("设置风扇为高速");
                duty = 10;
            }
            FanSpeed::Medium => {
                println!("设置风扇为中速");
                duty = 50;
            }
            FanSpeed::Low => {
                println!("设置风扇为低速");
                duty = 90;
            }
        }

        self.set_duty(duty);
    }
}
